package com.jiayi.microservice.service;

import com.jiayi.microservice.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author: CONCENTRATE
 * @time: 2018/11/4.
 */
@Service
public class ItemService {

    @Autowired
    private DiscoveryClient discoveryClient;

    private final static String ITEM_SERVICE = "microservice-item";

    @Autowired
    private RestTemplate restTemplate;
//
//    @Value("${micro.service.item.url}")
//    private String itemUrl;
//
//    public Item queryItemById(Long id){
//        return restTemplate.getForObject(itemUrl+ id, Item.class);
////        return restTemplate.getForObject("http://localhost:8080/item/"+ id, Item.class);
//    }
    public Item queryItemById(Long id){
        List<ServiceInstance> instances = discoveryClient.getInstances(ITEM_SERVICE);
        if(instances == null || instances.isEmpty()){
            return null;
        }
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort();
        Item item = restTemplate.getForObject(url + "/item/" + id, Item.class);

        return item;
//        return restTemplate.getForObject("http://localhost:8080/item/"+ id, Item.class);
    }
}
